<template>
  <view class="cyberpunk-container">
    <!-- 状态栏 -->
    <view class="status-bar">
      <text class="time">{{ currentTime }}</text>
      <view class="status-icons">
        <text class="network">{{ networkSpeed }} KB/s</text>
        <text class="battery">{{ batteryLevel }}</text>
      </view>
    </view>
    
    <!-- 顶部导航栏 -->
    <cyber-header 
      :title="'通信质量智能诊断'" 
      :subtitle="'QUANTUM SIGNAL ANALYZER'"
      @search="handleSearch"
      @userProfile="goToUserProfile"
    />
    
    <!-- 内容区域 -->
    <scroll-view scroll-y class="content-area">
      <!-- 核心诊断功能区 -->
      <view class="core-diagnostic-area">
        <!-- 一键诊断按钮 -->
        <view class="diagnostic-button-container">
          <view 
            class="diagnostic-button" 
            :class="{ 'diagnosing': isDiagnosing }"
            hover-class="button-hover" 
            @click="startDiagnostic"
          >
            <view class="button-inner">
              <text v-if="!isDiagnosing">立即诊断</text>
              <text v-else>{{ diagnosticStatus }}</text>
            </view>
          </view>
          <view class="pulse-ring" :class="{ 'active': isDiagnosing }"></view>
          
          <!-- 诊断进度环 -->
          <view v-if="isDiagnosing" class="progress-ring">
            <view class="progress-fill" :style="{ transform: `rotate(${diagnosticProgress * 3.6}deg)` }"></view>
          </view>
        </view>
        
        <!-- 实时诊断状态 -->
        <view v-if="isDiagnosing" class="diagnostic-status">
          <view class="status-item" v-for="(step, index) in diagnosticSteps" :key="index">
            <view class="status-icon" :class="step.status">
              <text v-if="step.status === 'completed'">✓</text>
              <text v-else-if="step.status === 'running'">⟳</text>
              <text v-else>○</text>
            </view>
            <text class="status-text">{{ step.name }}</text>
          </view>
        </view>
      </view>
      
      <!-- 快捷功能区 -->
      <view class="section-container">
        <text class="section-title">快捷功能</text>
        <cyber-quick-functions :functions="quickFunctions" @select="selectQuickFunction" />
      </view>
      
      <!-- 数据统计与展示区 -->
      <view class="section-container">
        <text class="section-title">网络状态</text>
        <view class="network-status">
          <view class="status-summary" :class="networkStatus.class">
            <uni-icons :type="networkStatus.icon" size="24" color="#00ffff"></uni-icons>
            <text>{{ networkStatus.text }}</text>
          </view>
        </view>
        
        <cyber-network-stats :stats="networkStats" />
      </view>
      
      <!-- 个性化推荐区 -->
      <view class="section-container">
        <text class="section-title">推荐优化</text>
        <cyber-recommendations :recommendations="recommendations" @select="viewRecommendation" />
      </view>
      
      <!-- 热门案例 -->
      <view class="section-container">
        <text class="section-title">热门案例</text>
        <cyber-cases :cases="popularCases" @select="viewCase" />
      </view>
      
      <!-- 底部空间 -->
      <view style="height: 50px;"></view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';

// 状态栏数据
const currentTime = ref('15:41');
const networkSpeed = ref('139');
const batteryLevel = ref('56');

// 诊断相关状态
const isDiagnosing = ref(false);
const diagnosticProgress = ref(0);
const diagnosticStatus = ref('立即诊断');

// 诊断步骤
const diagnosticSteps = reactive([
  { name: '网络连接检测', status: 'pending' },
  { name: '信号强度分析', status: 'pending' },
  { name: '速度测试', status: 'pending' },
  { name: '延迟测试', status: 'pending' },
  { name: '生成报告', status: 'pending' }
]);

// 固定的诊断结果数据
const getDemoResult = () => {
  return {
    networkType: 'wifi',
    isConnected: true,
    signalStrength: 87,
    downloadSpeed: 45.6,
    uploadSpeed: 36.8,
    latency: 23,
    packetLoss: 0.8,
    deviceInfo: {
      platform: 'android',
      system: 'Android 12',
      model: 'SM-G9980',
      brand: 'samsung',
      screenWidth: 1080,
      screenHeight: 2340,
      version: '12.0'
    },
    timestamp: new Date().toLocaleString(),
    overallScore: 92,
    recommendations: [
      '网络状况优秀，无需特别优化',
      '建议定期清理设备缓存以保持最佳性能',
      '可考虑升级到Wi-Fi 6路由器以获得更好体验'
    ]
  };
};

// 更新时间的函数
const updateTime = () => {
  const now = new Date();
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  currentTime.value = `${hours}:${minutes}`;
};

// 模拟网络速度变化
const updateNetworkSpeed = () => {
  networkSpeed.value = Math.floor(Math.random() * 200 + 50).toString();
};

// 定时器
let timeInterval = null;
let networkInterval = null;

onMounted(() => {
  updateTime();
  timeInterval = setInterval(updateTime, 60000);
  networkInterval = setInterval(updateNetworkSpeed, 10000);
});

onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval);
  if (networkInterval) clearInterval(networkInterval);
});

// 更新诊断步骤状态
const updateStepStatus = (stepIndex, status) => {
  diagnosticSteps[stepIndex].status = status;
};

// 更新进度和状态
const updateProgress = (progress, status) => {
  diagnosticProgress.value = progress;
  diagnosticStatus.value = status;
};

// 开始诊断（演示版本）
const startDiagnostic = async () => {
  if (isDiagnosing.value) return;
  
  isDiagnosing.value = true;
  diagnosticProgress.value = 0;
  
  // 重置所有步骤状态
  diagnosticSteps.forEach(step => step.status = 'pending');
  
  try {
    // 步骤1: 网络连接检测
    updateStepStatus(0, 'running');
    updateProgress(20, '检测网络连接...');
    await new Promise(resolve => setTimeout(resolve, 800));
    updateStepStatus(0, 'completed');
    
    // 步骤2: 信号强度分析
    updateStepStatus(1, 'running');
    updateProgress(40, '分析信号强度...');
    await new Promise(resolve => setTimeout(resolve, 1000));
    updateStepStatus(1, 'completed');
    
    // 步骤3: 速度测试
    updateStepStatus(2, 'running');
    updateProgress(60, '测试网络速度...');
    await new Promise(resolve => setTimeout(resolve, 1200));
    updateStepStatus(2, 'completed');
    
    // 步骤4: 延迟测试
    updateStepStatus(3, 'running');
    updateProgress(80, '测试网络延迟...');
    await new Promise(resolve => setTimeout(resolve, 800));
    updateStepStatus(3, 'completed');
    
    // 步骤5: 生成报告
    updateStepStatus(4, 'running');
    updateProgress(100, '生成诊断报告...');
    await new Promise(resolve => setTimeout(resolve, 600));
    updateStepStatus(4, 'completed');
    
    // 获取演示数据并跳转到结果页面
    // const demoResult = getDemoResult();
    uni.navigateTo({
      url: '/pages/result/result'
    });
    
  } catch (error) {
    console.error('诊断过程出错:', error);
    uni.showToast({
      title: '诊断失败，请重试',
      icon: 'none'
    });
  } finally {
    isDiagnosing.value = false;
    diagnosticProgress.value = 0;
    diagnosticStatus.value = '立即诊断';
    // 重置步骤状态
    diagnosticSteps.forEach(step => step.status = 'pending');
  }
};

// 其他数据保持不变
const diagnosticItems = reactive([
  { id: 1, title: '信号强度检测', icon: 'signal', description: '检测当前网络信号强度及稳定性' },
  { id: 2, title: '网络速度测试', icon: 'download', description: '测试上传和下载速度' },
  { id: 3, title: '丢包率分析', icon: 'error', description: '分析网络数据包传输丢失情况' },
  { id: 4, title: '基站距离评估', icon: 'location', description: '评估与最近基站的距离及信号质量' }
]);

const quickFunctions = reactive([
  { id: 1, title: '网络故障排查', icon: 'help' },
  { id: 2, title: 'Wi-Fi优化', icon: 'wifi' },
  { id: 3, title: '连接稳定性', icon: 'sync' },
  { id: 4, title: '历史记录', icon: 'calendar' }
]);

const networkStatus = reactive({
  text: '网络良好，信号稳定',
  icon: 'checkmark-circle',
  class: 'status-good'
});

const networkStats = reactive({
  signalStrength: 85,
  networkSpeed: 42.5,
  packetLoss: 2,
  latency: 28
});

const recommendations = reactive([
  { 
    id: 1, 
    title: 'Wi-Fi信号优化', 
    description: '您的Wi-Fi信号强度较弱，建议调整路由器位置或减少干扰源',
    icon: 'wifi'
  },
  { 
    id: 2, 
    title: '网络通道切换', 
    description: '当前网络通道拥堵，建议切换到其他通道以提高速度',
    icon: 'refresh'
  }
]);

const popularCases = reactive([
  { 
    id: 1, 
    title: '解决网络延迟高问题', 
    description: '用户通过更换网络通道解决了网络延迟高的问题',
    views: 1256
  },
  { 
    id: 2, 
    title: '提升Wi-Fi覆盖范围', 
    description: '通过优化路由器位置，用户成功提升了Wi-Fi信号覆盖范围',
    views: 983
  }
]);

// 其他方法
const handleSearch = (keyword) => {
  console.log('搜索关键词:', keyword);
  uni.showToast({
    title: `正在搜索: ${keyword}`,
    icon: 'none'
  });
};

const goToUserProfile = () => {
  try {
    uni.switchTab({
      url: '/pages/user/profile'
    });
  } catch (e) {
    console.error('页面跳转错误:', e);
    uni.showToast({
      title: '个人中心页面正在开发中',
      icon: 'none'
    });
  }
};

const selectQuickFunction = (func) => {
  console.log('选择快捷功能:', func);
  try {
    if (func.id === 4) {
      uni.switchTab({
        url: '/pages/history/index'
      });
    } else {
      uni.navigateTo({
        url: `/pages/function/detail?id=${func.id}&title=${func.title}`
      });
    }
  } catch (e) {
    console.error('页面跳转错误:', e);
    uni.showToast({
      title: `${func.title}功能正在开发中`,
      icon: 'none'
    });
  }
};

const viewRecommendation = (recommendation) => {
  console.log('查看推荐:', recommendation);
  try {
    uni.navigateTo({
      url: `/pages/recommendation/detail?id=${recommendation.id}`
    });
  } catch (e) {
    console.error('页面跳转错误:', e);
    uni.showToast({
      title: `${recommendation.title}页面正在开发中`,
      icon: 'none'
    });
  }
};

const viewCase = (caseItem) => {
  console.log('查看案例:', caseItem);
  try {
    uni.navigateTo({
      url: `/pages/case/detail?id=${caseItem.id}`
    });
  } catch (e) {
    console.error('页面跳转错误:', e);
    uni.showToast({
      title: `案例详情页面正在开发中`,
      icon: 'none'
    });
  }
};
</script>

<style>
.cyberpunk-container {
  background-color: #000;
  color: #fff;
  min-height: 100vh;
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
  background-color: rgba(0, 0, 0, 0.8);
  border-bottom: 1px solid rgba(0, 255, 255, 0.2);
  font-size: 12px;
  color: #00ffff;
}

.status-icons {
  display: flex;
  align-items: center;
}

.network {
  margin-right: 10px;
}

.content-area {
  height: calc(100vh - 90px);
  padding: 15px;
  box-sizing: border-box;
  width: 100%;
}

.core-diagnostic-area {
  margin-bottom: 20px;
}

.diagnostic-button-container {
  position: relative;
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.diagnostic-button {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff00ff, #00ffff);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3;
  box-shadow: 0 0 20px rgba(255, 0, 255, 0.5);
  transition: all 0.3s ease;
}

.diagnostic-button.diagnosing {
  animation: diagnosing-pulse 2s infinite;
}

@keyframes diagnosing-pulse {
  0%, 100% { 
    box-shadow: 0 0 20px rgba(255, 0, 255, 0.5);
  }
  50% { 
    box-shadow: 0 0 40px rgba(255, 0, 255, 0.8), 0 0 60px rgba(0, 255, 255, 0.6);
  }
}

.button-inner {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #00ffff;
  font-size: 16px;
  font-weight: bold;
  text-transform: uppercase;
  text-align: center;
  line-height: 1.2;
}

.button-hover .button-inner {
  background-color: rgba(0, 0, 0, 0.7);
}

.pulse-ring {
  position: absolute;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: transparent;
  border: 2px solid rgba(0, 255, 255, 0.5);
  z-index: 1;
}

.pulse-ring.active {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.8;
  }
  70% {
    transform: scale(1.1);
    opacity: 0;
  }
  100% {
    transform: scale(0.8);
    opacity: 0;
  }
}

.progress-ring {
  position: absolute;
  width: 140px;
  height: 140px;
  border-radius: 50%;
  background: conic-gradient(from 0deg, transparent, transparent);
  z-index: 2;
}

.progress-fill {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: conic-gradient(from 0deg, #00ffff 0deg, transparent 0deg);
  transition: transform 0.3s ease;
}

.diagnostic-status {
  background: rgba(0, 0, 0, 0.8);
  border: 1px solid rgba(0, 255, 255, 0.3);
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-icon {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 12px;
  font-weight: bold;
}

.status-icon.pending {
  background: rgba(255, 255, 255, 0.2);
  color: #666;
}

.status-icon.running {
  background: #ffff00;
  color: #000;
  animation: spin 1s linear infinite;
}

.status-icon.completed {
  background: #00ff00;
  color: #000;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.status-text {
  color: #fff;
}

.section-container {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.section-title {
  font-size: 18px;
  color: #ff00ff;
  margin-bottom: 10px;
  display: block;
  position: relative;
  padding-left: 15px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 18px;
  background: linear-gradient(to bottom, #ff00ff, #00ffff);
}

.network-status {
  margin-bottom: 15px;
}

.status-summary {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border-radius: 5px;
  background-color: rgba(0, 0, 0, 0.5);
}

.status-summary text {
  margin-left: 10px;
  color: #00ffff;
}

.status-good {
  border-left: 3px solid #00ff00;
}

.status-warning {
  border-left: 3px solid #ffff00;
}

.status-error {
  border-left: 3px solid #ff0000;
}
</style>